import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App.tsx'
import './index.css'

// PWA Service Worker 注册
if ('serviceWorker' in navigator) {
  window.addEventListener('load', () => {
    navigator.serviceWorker.register('/sw.js')
      .then((registration) => {
        console.log('✅ Service Worker 注册成功:', registration.scope);
        
        // 监听Service Worker消息
        navigator.serviceWorker.addEventListener('message', (event) => {
          if (event.data.type === 'GET_AUTH_TOKEN') {
            const token = localStorage.getItem('token');
            event.ports[0].postMessage({ token });
          }
        });
        
        // 通知Service Worker客户端已激活
        if (registration.active) {
          registration.active.postMessage({ type: 'CLIENT_ACTIVE' });
        }
      })
      .catch((error) => {
        console.error('❌ Service Worker 注册失败:', error);
      });
  });

  // 页面卸载时通知Service Worker
  window.addEventListener('beforeunload', () => {
    navigator.serviceWorker.ready.then((registration) => {
      if (registration.active) {
        registration.active.postMessage({ type: 'CLIENT_INACTIVE' });
      }
    });
  });
}

ReactDOM.createRoot(document.getElementById('root')!).render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
)
